package com.da.util;

import java.io.Serializable;

import javax.annotation.Resource;

import org.hibernate.EmptyInterceptor;
import org.hibernate.type.Type;
import org.springframework.stereotype.Service;

import com.ra.landlord.LandlordOwner;
import com.ra.landlord.LandlordOwnerUser;
import com.ra.landlord.LandlordUser;
import com.ra.landlord.LandlordUserService;
import com.ra.system.Version;

@Service
public class DaEntityInterceptor extends EmptyInterceptor {
	
	@Resource
	private LandlordUserService landlordUserService;

	public boolean onSave(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types) {
		return updateLandlordUser(entity, state, propertyNames);
	}

	private boolean updateLandlordUser(Object entity, Object[] state, String[] propertyNames) {
		boolean modified = false;
		
		if (entity instanceof LandlordOwner || entity instanceof Version) {
			LandlordOwnerUser landlordUser = null;
			for (int i = 0; i < propertyNames.length; i++) {
				if (state[i] == null) {
					String propertyName = propertyNames[i];
					if ("landlordUser".equals(propertyName)) {
						LandlordUser user = landlordUserService.getLoginUser();
						if (user != null) {
							landlordUser = user.getOwnerUser();
							state[i] = landlordUser;
							modified = true;
						}
					} else if ("status".equals(propertyName)) {
						state[i] = Version.STATUS_VALID;
						modified = true;
					} else if ("version".equals(propertyName)) {
						Integer version = null;
						//特为PC端的改动，以后移除
						if (state[i] == null) {
							version = 1;
						} else {
							version = (Integer)state[i] + 1;
						}
						state[i] = version;
						modified = true;
					}
				}
			}
		}
		
		return modified;
	}
	
	@Override
	public boolean onFlushDirty(Object entity, Serializable id, Object[] currentState, Object[] previousState,
			String[] propertyNames, Type[] types) {
		return updateLandlordUser(entity, currentState, propertyNames);
	}
}